package com.cjh.common.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjh.common.config.RedisKey;
import com.cjh.common.service.UploadService;
import com.cjh.common.wxDto.UpdateWxUserDto;
import com.cjh.common.wxDto.WXAuth;
import com.cjh.common.wxDto.WxUserDto;
import com.cjh.common.entity.WxUser;
import com.cjh.common.response.Result;
import com.cjh.common.service.WxUserService;
import com.cjh.common.mapper.WxUserMapper;
import com.cjh.common.utils.JWTUtils;
import com.cjh.common.utils.WxDecrypt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class WxUserServiceImpl extends ServiceImpl<WxUserMapper, WxUser>
    implements WxUserService{
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    WxUserMapper wxUserMapper;
    @Autowired
    UploadService uploadService;
    @Override
    public String getSessionId(String code,String secret, String appid) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        url = url.replace("{0}", appid).replace("{1}", secret).replace("{2}", code);
        String res = HttpUtil.get(url);
        String s = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(RedisKey.WX_SESSION_ID + s, res,30, TimeUnit.MINUTES);
        return s;
    }
    @Override
    public Result authLogin(WXAuth wxAuth) {
        try {
            String json = redisTemplate.opsForValue().get(RedisKey.WX_SESSION_ID + wxAuth.getSessionId());
            JSONObject jsonObject = JSON.parseObject(json);
            if(jsonObject == null){
                return new Result().setCode(1).setMessage("身份授权失败，请重新授权登录!");
            }
            String openid = (String) jsonObject.get("openid");
            //判断数据库是否有该用户，有即登录，没有即注册
            WxUser wxUser1 = wxUserMapper.selectOne(Wrappers.<WxUser>lambdaQuery().eq(WxUser::getOpenid, openid));
            if (wxUser1 != null) {
                //登录成功
                WxUserDto userDto = new WxUserDto();
                BeanUtils.copyProperties(wxUser1,userDto);
                return new Result().setCode(0).setMessage("登录成功!").setData(this.login(userDto));
            } else {
                //解析用户信息
                String sessionKey = (String) jsonObject.get("session_key");
                String wxRes = WxDecrypt.wxDecrypt(wxAuth.getEncryptedData(), sessionKey, wxAuth.getIv());
                WxUser wxUser = JSON.parseObject(wxRes, WxUser.class);
                String s = uploadService.uploadOnlineFileToLocal(wxUser.getAvatarUrl(), "wxUserAvatar/");
                wxUser.setAvatarUrl(s);
                wxUser.setOpenid(openid);
                wxUserMapper.insert(wxUser);
                WxUserDto userDto = new WxUserDto();
                BeanUtils.copyProperties(wxUser,userDto);
                return new Result().setCode(0).setMessage("登录成功!").setData(this.login(userDto));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result().setCode(1).setMessage("操作失败!");
    }

    public WxUserDto login(WxUserDto wxUserDto) {
        // 登录成功 封装用户信息到token
        String token = JWTUtils.sign(Long.valueOf(wxUserDto.getId()));
        wxUserDto.setToken(token);
        //保存到redis内,下次就直接跳过验证
        redisTemplate.opsForValue().set(RedisKey.TOKEN_KEY + token, JSON.toJSONString(wxUserDto), 7, TimeUnit.DAYS);
        return wxUserDto;
    }

    @Override
    public Result userinfo(Boolean refresh, WxUserDto wxUserDto) {
        if( refresh ){
            WxUser wxUser1 = wxUserMapper.selectOne(Wrappers.<WxUser>lambdaQuery().eq(WxUser::getId, wxUserDto.getId()));
            BeanUtils.copyProperties(wxUser1,wxUserDto);
            redisTemplate.opsForValue().set(RedisKey.TOKEN_KEY + wxUserDto.getToken(),JSON.toJSONString(wxUserDto),7,TimeUnit.DAYS);
        }
        return new Result().setCode(0).setMessage("获取成功!").setData(wxUserDto);
    }

    @Override
    public Result updateUser(UpdateWxUserDto updateWxUserDto) {
        WxUser wxUser = new WxUser();
        BeanUtils.copyProperties(updateWxUserDto,wxUser);
        wxUserMapper.updateById(wxUser);
        return new Result().setCode(0).setMessage("修改成功!");
    }
}




